# -*- coding: utf-8 -*-
"""\
cSAXS data preparation script, new flavor.
"""
import sys
import ptycho2 as ptycho
import numpy as np

def prep_eiger_file(base_path,user,dpsize,ctr,detector_distance,first_scan,last_scan,step_size_y,sx,nx,dat_file):
    # Need to "hack" the defaults for continuous scans
    ptycho.cSAXS.FILENAME_PATTERN = '{read_path}/{prefix}{scan_number:05d}_{index}_00000.{file_extension}'

    # Empty parameter structure
    p = ptycho.Param()

    p.verbose_level = 3
    p.interactive = False                         # Not used for now
    p.base_path = base_path
    p.user = user
    #p.scan_number = 300
    p.dpsize = dpsize                          # Crop size (used to be "asize")
    p.ctr = ctr                               # Center of cropped array
    #p.motors = ('py', 'px')                      # Motor names in y and x
    #p.motors_multiplier = 1e-3                    # Multiplier to convert motor values to meters
    p.motors = None                               # Motor names in y and x
    p.energy = 6.2                                # Energy in keV
    p.detector_pixel_size = 75e-6                # Detector pixel size
    p.detector_distance = detector_distance                    # Detector distance
    p.scan_type = 'raster'                            # None (use spec), or 'raster', 'round', 'round_ROI'
    p.scan_params.nx = nx
    p.scan_params.ny = 0
    p.scan_params.step_size_x = sx
    p.scan_params.step_size_y = step_size_y
    p.spec_filename = ptycho.cSAXS.spec.SpecInfo(base_path + '/specES1/dat-files/'+dat_file)
    p.pilatus_dir = 'eiger'
    p.pilatus_mask = base_path + '/matlab/ptycho/eiger_valid_mask.mat'
#    p.pilatus_mask = base_path + '/eiger_valid_mask.mat'
    p.isEigerFile = True
#    p.isEigerRoundScan = True
#    specinfo = ptycho.cSAXS.spec.SpecInfo(base_path + '/specES1/dat-files/'+dat_file)

    for kk in range(first_scan,last_scan+1):
        p.scan_number = kk
        ptycho.cSAXS.prepare_data(p)

    scan_label = 'S%05d_S%05d' % (first_scan, last_scan)

    fpattern = base_path + '/analysis/S%05d/S%05d_data_' + '%dx%d.h5' % dpsize

    # Load all data as dataScan objects
    ds_all = [ptycho.experiment.DataScan(fpattern % (i,i)) for i in range(first_scan, last_scan+1)]

    # The "out" scan will be based on one of these
    ds = ptycho.experiment.DataScan(fpattern % (first_scan,first_scan))

    # Now modify the structure
    # First combine data
    ds.data = np.concatenate([di.data for di in ds_all])
    ds.scan_info.shape = ds.data.shape
    ds.scan_info.scan_label = scan_label

    # Edit positions
    positions = np.concatenate([ds_all[i].scan_info.positions_theory + [0., i*step_size_y] for i in range(len(ds_all))])[:,-1::-1]
    ds.scan_info.positions = positions
    ds.scan_info.positions_theory = positions

    ds.scan_info.data_filename = base_path + '/analysis/%s/%s_data_' % (scan_label, scan_label) + '%dx%d.h5' % dpsize

    # little bug that needs to be solved7.18
    ds.mask = ds.fmask
    ds.save()

user = 'e14438'
dpsize = (460,460)
ctr = (280, 375)
detector_distance= 7.2122
first_scan = 9185
last_scan = 9185
base_path = '/space/ptychography/S12686/'
#base_path = '/home/philipp/Documents/master'
dat_file = 'specES1_started_2013_03_20_1108.dat'
scan = (first_scan,25)
size = size = 5e-6

prep_eiger_file(base_path, user, dpsize, ctr, detector_distance, scan[0], scan[0]+scan[1], size/scan[1],size/(scan[1]+1),scan[1],dat_file)
